package com.yf.controller;

import com.yf.bean.UserRegCodeBean;
import com.yf.dao.UserRegCodeDao;
import com.yf.service.RedisService;
import com.yf.utils.Utils;
import com.yf.utils.WxXmlParser;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.MurmurHash3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Log4j2
@RestController
@RequestMapping(value = "${custom.api-version}")
public class WeChatController {
    private static final String regCodeKey = "注册码";
    @Autowired
    RedisService redisService;

    @Autowired
    UserRegCodeDao userRegCodeDao;

    @GetMapping("/wechat")
    public String hello(
            @RequestParam(value = "signature", defaultValue = "#") String signature,
            @RequestParam(value = "timestamp", defaultValue = "#") String timestamp,
            @RequestParam(value = "nonce", defaultValue = "#") String nonce,
            @RequestParam(value = "echostr", defaultValue = "#") String echostr) {
        log.warn("receive from wechat:" + signature + " " + timestamp + " " + nonce + " " + echostr);
        return echostr;
    }

    @PostMapping("/wechat")
    public String autoReply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF8");
        ServletInputStream inputStream = request.getInputStream();
        Map<String, String> params = WxXmlParser.parseWxTxtContent(inputStream);
        if (params == null) {
            return "success";
        }
        String user = params.get("ToUserName");
        String from = params.get("FromUserName");
        String content = params.get("Content");
        if (user == null || from == null || content == null)  {
            return "success";
        }
        if (!regCodeKey.equals(content)) {
            return "success";
        }

        log.info("From wx:" + from);

        UserRegCodeBean wxUser = new UserRegCodeBean();
        wxUser.setUid(from);
        wxUser.setUidHash(MurmurHash3.hash32x86(from.getBytes()));

        String regCode;
        boolean hasApplied = userRegCodeDao.existed(wxUser) > 0;
        if (hasApplied) {
            regCode = "您已经获取过注册码";
        } else {
            regCode = redisService.getRegCode();
            if (regCode == null) {
                regCode = "获取注册码失败";
            }
            wxUser.setCreated(Utils.currentTime());
            userRegCodeDao.add(wxUser);
        }
        String replyMsg = "注册码:" + regCode;
        String toUser = String.format("<ToUserName><![CDATA[%s]]></ToUserName>", from);
        String fromUser = "<FromUserName><![CDATA[csapp_go]]></FromUserName>";
        String create = String.format("<CreateTime>%d</CreateTime>", (int) (System.currentTimeMillis() / 1000));
        String MsgType = "<MsgType><![CDATA[text]]></MsgType>";
        String Content = String.format("<Content><![CDATA[%s]]></Content>", replyMsg);
        return String.format("<xml>%s%s%s%s%s</xml>", toUser, fromUser, create, MsgType, Content);
    }
}
